import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
import NProgress from '@/utils/nprogress'
import userStore from '@/store/user'
import permissionStore from '@/store/permission'
import { permissions } from './permission'
import { IRouter } from './type'
import { dealRouteData } from './util';
import { getUserPermission } from '@/api/common'

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'site',
        component: Layout,
        redirect: '/middleware',
        children: []
    },
    {
        path: '/middleware',
        name: 'Middleware',
        component: () => import('@/views/middleware/index.vue'),
        meta: {
            title: '转接',
            isAuth: true
        }
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue'),
        meta: {
            title: '登录',
            isAuth: true
        }
    },
    {
        path: '/error',
        name: 'Error',
        component: () => import('@/views/error/index.vue'),
        meta: {
            title: '页面不存在',
            isAuth: true
        }
    }
]

const router = createRouter({
    routes,
    history: createWebHistory()
})

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    // 检查用户是否已登录
    //❗️避免无限重定向
    // 是否白名单
    //用户信息
    const userInfo = userStore();
    let { token } = userInfo;
    let { isAuth } = to.meta
    if (!token) {
        if(!isAuth && to.path != '/login'){
            // 将用户重定向到登录页面
            next('/login')
        }
        next();
    } else {
        const permissionInfo = permissionStore();
        //获取路由信息
        let { routes } = permissionInfo;
        if (routes && routes.length) {
            next();
        } else {
            try {
                //此处应该有请求路由权限的接口
                let res = await getUserPermission();
                let {data} = res;
                var routerInfo = dealRouteData(data);
                permissionInfo.updateRoutes(data)
                let { accessedRouters } = routerInfo;
                accessedRouters.forEach((item: IRouter) => {
                    let {extend} = item;
                    let routerItem: RouteRecordRaw = {
                        path: item.path,
                        name: item.name,
                        component: item.component,
                        meta: item.meta
                    }
                    if(extend){
                        router.addRoute(routerItem)
                    }else{
                        router.addRoute("site", routerItem)
                    }
                })
                next({ ...to, replace: true });
                NProgress.done();
            } catch (err) {
                next(`/login`);
            }
        }
    }
})
router.afterEach(() => {
    NProgress.done()
});

export default router
